package com.dodayum.controller;

import com.dodayum.service.AnnotationsDemoServiceImpl;
import com.dodayum.service.DemoRegistry;
import com.dodayum.service.DemoRegistryService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRange;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.util.List;

@RestController
@RequestMapping
public class DemoController {

    @Resource
    private AnnotationsDemoServiceImpl annotationsDemoService;

    @Resource
    private DemoRegistry demoRegistry;

    @GetMapping("/demo/{time}")
    public String demo(@PathVariable("time") Long time) throws Exception {
        return annotationsDemoService.timeTest(time);
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestHeader(value = "Range", required = false) String rangeHeader,
                                               @RequestParam("fileName") String fileName,
                                               HttpServletResponse response) throws IOException {
        File file = new File(fileName);
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        long fileLength = file.length();
        // 分片信息
        List<HttpRange> ranges = HttpRange.parseRanges(rangeHeader);
        HttpRange range = ranges.get(0);
        long start = range.getRangeStart(fileLength);
        long end = range.getRangeEnd(fileLength);
        long rangeLength = end - start + 1;

        // 放数据
        byte[] data;
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            raf.seek(start);
            data = new byte[(int) rangeLength];
            raf.readFully(data);
        }

        // 设置响应头信息
        response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + fileLength);
        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        String contentType = Files.probeContentType(file.toPath());
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                .header(HttpHeaders.CONTENT_TYPE, contentType) // Content-Type
                .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(rangeLength)) // 总长度
                .body(data);
    }

    @GetMapping("/aaa/{input}")
    public void aaa(@PathVariable String input) throws Exception {
        DemoRegistryService a = demoRegistry.getDemoRegistryService(input);
        a.sayHello();
    }

}
